package com.shine.level.easy;

import java.util.Arrays;
import java.util.Comparator;

/**最长公共前缀解法2:
 * 先排序在检索
 * @author zhangshao
 * @date 2021/6/28 5:54 下午
 */
public class longestCommonPrefixTest2 {
    /**
     * 自定义比较器
     * 按照字典序排序
     */
    public static class MyComparator implements Comparator<String>{

        @Override
        public int compare(String a, String b) {
            return a.compareTo(b);
        }
    }
    public static String longestCommonPrefix(String[] strs){
        if(strs == null || strs.length ==0){
            return "";
        }
        if(strs.length ==1){
            return strs[0];
        }
        Arrays.sort(strs,new MyComparator());
        String first = strs[0] ,last = strs[strs.length-1];

        int len = Math.min(first.length(),last.length());

        for(int i=0;i<len;i++){
            if(first.charAt(i)!=last.charAt(i)){
                return first.substring(0,i);
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String [] strs = {"flowers","eggs"};
        String s = longestCommonPrefix(strs);
        System.out.println(s);

    }
}
